<?php
namespace common\services;

use Yii;
use common\base\BaseActiveRecord;
use common\helpers\TStringHelper;
use common\models\ExhibitionPicture;
use yii\data\ActiveDataProvider;
use yii\data\Pagination;

class ExhibitionPictureServices extends ExhibitionPicture
{

    /**
     * 获取展会图片
     * @param $exhibition_id
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getExhibitionPictureByEid($exhibition_id) {
        $model = ExhibitionPicture::find(false);
        $model->andFilterWhere(['=', 'status', ExhibitionPicture::STATUS_FLAG_NORMAL])
            ->andFilterWhere(['=', 'exhibition_id', $exhibition_id])
            ->select([
                'filename' => 'name',
                'fileUrl' => 'litpic'
            ])
        ->asArray()
        ->orderBy('id asc');

        return $model->all();
    }

    /**
     * 添加展会图片
     * @param $exhibition_id
     * @param $data
     * @return bool
     */
    public function setExhibitionPicture($exhibition_id, $data) {
        if (empty($exhibition_id) || empty($data)) return false;
        //ExhibitionPicture::updateAll(['status' => ExhibitionPicture::STATUS_FLAG_STOP],'exhibition_id=:exhibition_id', [':exhibition_id' => $exhibition_id]);
        //物理删除
        Yii::$app->db->createCommand()->delete(ExhibitionPicture::tableName(), 'exhibition_id=:exhibition_id', [':exhibition_id' => $exhibition_id])->execute();
        if (empty($data)) return false;
        if (!is_array($data)) {
            $data = json_decode($data, true);
        }

        $batchInsert = [];
        $root = \Yii::$app->basePath.'/..';
        $data = array_filter($data);
        foreach ($data as $val) {
            $json = @json_decode($val, true);
            if (!is_array($json)) continue;
            $model = new ExhibitionPicture();
            $model->exhibition_id = $exhibition_id;
            $model->name = $json['filename'];
            $model->litpic = $json['fileUrl'];
            $model->md5 = hash_file('md5', $root.$json['fileUrl']);
            $model->extension = end(explode('.', $json['fileUrl']));
            array_push($batchInsert, $model);
        }
        //批量添加数据
        if (!empty($batchInsert) ) {
            BaseActiveRecord::batchInsertSqlArray($batchInsert);
        }
        return true;

    }

}
